package cn.itcast.search.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ItemListener {
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.down"),
            exchange = @Exchange(name = "item.exchange", type = ExchangeTypes.DIRECT),
            key = {"down"}
    ))
    public void down(Long id) {
        //构建请求
        DeleteRequest item = new DeleteRequest("item", id.toString());


        try {
            DeleteResponse delete = client.delete(item, RequestOptions.DEFAULT);
            System.out.println(delete.status());
            log.info("删除id为{}的文档",id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.up"),
            exchange = @Exchange(name = "item.exchange", type = ExchangeTypes.DIRECT),
            key = {"up"}
    ))
    public void up(String s) {
        //构建请求
        Object parse = JSON.parse(s);
        System.err.println(s);

        String[] split = s.split(",");
        String idStr=null;
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
            if (split[i].startsWith("\"id\":")){idStr=split[i];break;}
        }
        System.out.println(idStr);

        String[] split1 = idStr.split(":");
        System.out.println(split1[1]);


        IndexRequest item = new IndexRequest("item").id(split1[1]);

        item.source(s, XContentType.JSON);

        try {
            IndexResponse index = client.index(item, RequestOptions.DEFAULT);
            RestStatus status = index.status();
            System.out.println(status);
            log.info("添加id为{}的文档",idStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
